import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Button,
  Space,
  Typography,
  Tag,
  Progress,
  message,
  Modal,
  Badge,
} from 'antd';
import {
  EyeOutlined,
  HeartOutlined,
  UserOutlined,
  MessageOutlined,
  EnvironmentOutlined,
  CrownOutlined,
} from '@ant-design/icons';
import { User } from '@/types';
import { getAvatarUrl } from '@/utils';
import { useNavigate, useLocation } from 'react-router-dom';

const { Title, Text } = Typography;

const SearchResult: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<User[]>([]);

  // Mock search results
  const mockResults: User[] = [
    {
      id: '1',
      nickname: '李小花',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female1',
      age: 26,
      gender: 'female',
      education: '本科',
      occupation: '设计师',
      city: '北京',
      height: 165,
      income: 15000,
      profileStatus: 'approved',
      registerTime: '2024-01-15T10:30:00Z',
      lastLoginTime: '2024-01-20T14:25:00Z',
      isVip: true,
      tags: ['旅行', '摄影', '美食'],
      introduction: '热爱生活的设计师，喜欢旅行和摄影',
      photos: ['https://picsum.photos/300/400?random=1'],
    },
    {
      id: '2',
      nickname: '王明',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male1',
      age: 28,
      gender: 'male',
      education: '硕士',
      occupation: '工程师',
      city: '北京',
      height: 175,
      income: 25000,
      profileStatus: 'approved',
      registerTime: '2024-01-14T09:15:00Z',
      lastLoginTime: '2024-01-19T16:45:00Z',
      isVip: false,
      tags: ['运动', '科技', '电影'],
      introduction: '程序员，喜欢运动和科技产品',
      photos: ['https://picsum.photos/300/400?random=2'],
    },
    {
      id: '3',
      nickname: '张丽',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female2',
      age: 24,
      gender: 'female',
      education: '本科',
      occupation: '教师',
      city: '上海',
      height: 160,
      income: 12000,
      profileStatus: 'approved',
      registerTime: '2024-01-13T11:20:00Z',
      lastLoginTime: '2024-01-18T13:30:00Z',
      isVip: true,
      tags: ['读书', '音乐', '健身'],
      introduction: '小学教师，喜欢读书和音乐',
      photos: ['https://picsum.photos/300/400?random=3'],
    },
    {
      id: '4',
      nickname: '陈志强',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male2',
      age: 30,
      gender: 'male',
      education: '硕士',
      occupation: '医生',
      city: '上海',
      height: 178,
      income: 35000,
      profileStatus: 'approved',
      registerTime: '2024-01-12T08:45:00Z',
      lastLoginTime: '2024-01-17T19:20:00Z',
      isVip: false,
      tags: ['健身', '音乐', '科技'],
      introduction: '外科医生，工作之余喜欢健身',
      photos: ['https://picsum.photos/300/400?random=4'],
    },
  ];

  const handleViewDetail = (user: User) => {
    navigate(`/user/detail/${user.id}`);
  };

  const handleMatch = (user: User) => {
    Modal.confirm({
      title: '确认发起匹配',
      content: `确定要为 ${user.nickname} 创建匹配推荐吗？`,
      onOk: () => {
        message.success(`已为 ${user.nickname} 创建匹配推荐`);
      },
    });
  };

  const handleSendMessage = (user: User) => {
    Modal.confirm({
      title: '发送消息',
      content: `确定要向 ${user.nickname} 发送消息吗？`,
      onOk: () => {
        message.success(`消息已发送给 ${user.nickname}`);
      },
    });
  };

  const calculateCompatibilityScore = (user: User): number => {
    // Simple compatibility calculation based on user attributes
    let score = 70; // base score
    
    // Add bonus for VIP users
    if (user.isVip) score += 10;
    
    // Add bonus for complete profiles
    if (user.photos && user.photos.length > 0) score += 5;
    if (user.introduction && user.introduction.length > 20) score += 5;
    if (user.tags && user.tags.length >= 3) score += 5;
    
    // Add some randomness
    score += Math.floor(Math.random() * 10);
    
    return Math.min(score, 100);
  };

  const getScoreColor = (score: number) => {
    if (score >= 90) return '#52c41a';
    if (score >= 80) return '#fa8c16';
    if (score >= 70) return '#1890ff';
    return '#ff4d4f';
  };

  useEffect(() => {
    setLoading(true);
    // Simulate API call
    setTimeout(() => {
      setSearchResults(mockResults);
      setLoading(false);
    }, 500);
  }, []);

  const resultCount = location.state?.resultCount || searchResults.length;

  return (
    <div className="page-container">
      <div className="page-header">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Title level={4} className="page-title">搜索结果</Title>
            <Text className="page-description">
              找到 {resultCount} 个匹配结果，按匹配度排序
            </Text>
          </div>
          <Button onClick={() => navigate('/search/advanced')}>
            返回搜索
          </Button>
        </div>
      </div>

      {/* Results Stats */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                {searchResults.length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>总结果数</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                {searchResults.filter(u => u.isVip).length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>VIP用户</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>
                {Math.round(searchResults.reduce((acc, u) => acc + calculateCompatibilityScore(u), 0) / searchResults.length) || 0}%
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>平均匹配度</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#eb2f96' }}>
                {searchResults.filter(u => u.photos && u.photos.length > 0).length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>有照片用户</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* Search Results */}
      <Row gutter={[16, 16]}>
        {searchResults.map((user) => {
          const compatibilityScore = calculateCompatibilityScore(user);
          return (
            <Col xs={24} sm={12} lg={8} xl={6} key={user.id}>
              <Card
                hoverable
                loading={loading}
                style={{ height: '100%' }}
                bodyStyle={{ padding: '16px' }}
                cover={
                  <div style={{ position: 'relative', height: '200px', overflow: 'hidden' }}>
                    {user.photos && user.photos.length > 0 ? (
                      <img
                        alt={user.nickname}
                        src={user.photos[0]}
                        style={{
                          width: '100%',
                          height: '100%',
                          objectFit: 'cover',
                        }}
                      />
                    ) : (
                      <div style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        backgroundColor: '#f5f5f5',
                      }}>
                        <Avatar
                          size={80}
                          src={getAvatarUrl(user.avatar, user.gender)}
                          icon={<UserOutlined />}
                        />
                      </div>
                    )}
                    
                    {/* VIP Badge */}
                    {user.isVip && (
                      <Badge.Ribbon text="VIP" color="gold" style={{ top: '8px', right: '8px' }} />
                    )}
                    
                    {/* Compatibility Score */}
                    <div style={{
                      position: 'absolute',
                      bottom: '8px',
                      right: '8px',
                      background: 'rgba(0,0,0,0.7)',
                      borderRadius: '16px',
                      padding: '4px 8px',
                    }}>
                      <Text style={{ color: 'white', fontSize: '12px', fontWeight: 'bold' }}>
                        匹配度 {compatibilityScore}%
                      </Text>
                    </div>
                  </div>
                }
              >
                <div style={{ height: '200px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                  {/* User Info */}
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                      <Title level={5} style={{ margin: 0, marginRight: '8px' }}>
                        {user.nickname}
                      </Title>
                      {user.isVip && <CrownOutlined style={{ color: '#faad14' }} />}
                    </div>
                    
                    <Space direction="vertical" size={4} style={{ width: '100%' }}>
                      <Text type="secondary">
                        {user.age}岁 • {user.gender === 'male' ? '男' : '女'} • {user.height}cm
                      </Text>
                      <Text type="secondary">
                        {user.education} • {user.occupation}
                      </Text>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <EnvironmentOutlined style={{ fontSize: '12px', marginRight: '4px' }} />
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          {user.city}
                        </Text>
                      </div>
                      {user.income && (
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          月收入: {user.income.toLocaleString()}元
                        </Text>
                      )}
                    </Space>

                    {/* Compatibility Progress */}
                    <div style={{ margin: '12px 0' }}>
                      <Progress
                        percent={compatibilityScore}
                        size="small"
                        strokeColor={getScoreColor(compatibilityScore)}
                        format={() => `${compatibilityScore}%`}
                      />
                    </div>

                    {/* Tags */}
                    <div style={{ marginBottom: '12px' }}>
                      {user.tags?.slice(0, 3).map((tag, index) => (
                        <Tag key={index} size="small" style={{ marginBottom: '4px' }}>
                          {tag}
                        </Tag>
                      ))}
                      {user.tags && user.tags.length > 3 && (
                        <Tag size="small">+{user.tags.length - 3}</Tag>
                      )}
                    </div>

                    {/* Introduction */}
                    {user.introduction && (
                      <Text
                        type="secondary"
                        style={{
                          fontSize: '12px',
                          display: 'block',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        {user.introduction}
                      </Text>
                    )}
                  </div>

                  {/* Action Buttons */}
                  <div style={{ marginTop: '12px' }}>
                    <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                      <Button
                        size="small"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(user)}
                      >
                        详情
                      </Button>
                      <Button
                        size="small"
                        type="primary"
                        icon={<HeartOutlined />}
                        onClick={() => handleMatch(user)}
                      >
                        匹配
                      </Button>
                      <Button
                        size="small"
                        icon={<MessageOutlined />}
                        onClick={() => handleSendMessage(user)}
                      >
                        消息
                      </Button>
                    </Space>
                  </div>
                </div>
              </Card>
            </Col>
          );
        })}
      </Row>

      {searchResults.length === 0 && !loading && (
        <Card>
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <UserOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }} />
            <div>
              <Text type="secondary">没有找到符合条件的用户</Text>
              <br />
              <Button
                type="link"
                onClick={() => navigate('/search/advanced')}
                style={{ marginTop: '8px' }}
              >
                调整搜索条件
              </Button>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
};

export default SearchResult;